<?php

class SystemUtil {

  public static function beginDoctrineTransaction($database = 'doctrine') {
    $connection = sfContext::getInstance()->getDatabaseManager()->getDatabase($database)->getDoctrineConnection();
    $connection->beginTransaction();
    return $connection;
  }

  public static function commitDoctrineTransaction(Doctrine_Connection $connection) {
    $connection->commit();
  }

  public static function rollbackDoctrineTransaction(Doctrine_Connection $connection) {
    $connection->rollback();
  }

  public static function getCurrentRouteName() {
    return sfContext::getInstance()->getRouting()->getCurrentRouteName();
  }

  public static function arrayDiffOnce() {
    if (($args = func_num_args()) < 2) {
      return false;
    }
    $arr1 = func_get_arg(0);
    $arr2 = func_get_arg(1);
    if (!is_array($arr1) || !is_array($arr2)) {
      return false;
    }
    foreach ($arr2 as $remove) {
      foreach ($arr1 as $k => $v) {
        if ((string) $v === (string) $remove) {
          unset($arr1[$k]);
          break;
        }
      }
    }
    $c = $args;
    while ($c > 2) {
      $c--;
      $arr1 = array_diff_once($arr1, func_get_arg($args - $c + 1));
    }
    return $arr1;
  }

  public static function calcSoldPercentage($totalTickets, $availableTickers) {
    return round(((($totalTickets-$availableTickers)/$totalTickets)*100), 1);
  }

  public static function generatePurchaseLink(OFFER $offer, MOVIE $movie, $isAbsolute = false) {
    return sfContext::getInstance()->getController()->genUrl('@purchase?id=' . $offer->getId() . '-' . StringUtil::slugify($movie->getTitle()), $isAbsolute);
  }

  public static function sendAlertEmail($subject, $message) {
    $email = new EMAIL();
    $email->setEmailTo(sfConfig::get('app_emailgroup_warning'));
    $email->setSubject($subject);
    $email->setMessage(array('content' => $message));
    $email->setTemplateFile('alertEmail');
    $email->setContentType(emailTask::CONTENT_TYPE_HTML);
    $email->save();
  }
}